package vote.ai.factory;

import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import vote.ai.domain.enums.CorrectionModel;
import vote.ai.service.AiCorrectionService;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Description:ai服务工厂类
 * Author:han
 * Date: 2024-05-21
 */
@Service
public class AiServiceFactory {
    private final Map<CorrectionModel, AiCorrectionService> correctionServiceMap;

    public AiServiceFactory(ApplicationContext context) {
        //从Spring容器中获取所有实现AiCorrectionService接口的bean
        //组装成Map
        Map<String, AiCorrectionService> beans = context.getBeansOfType(AiCorrectionService.class);
        correctionServiceMap = Arrays.stream(CorrectionModel.values())
                .filter(model -> beans.containsKey(model.getBeanName())) // 仅保留有对应 Bean 的枚举
                .collect(Collectors.toMap(
                        Function.identity(),
                        model -> beans.get(model.getBeanName())
                ));
        System.out.println("初始化了bean"+correctionServiceMap);
    }

    public AiCorrectionService getService(CorrectionModel model) {
        return Optional.ofNullable(correctionServiceMap.get(model))
                .orElseThrow(() -> new IllegalArgumentException("无效的策略类型: " + model));
    }

    /**
     * 判断是否有开启的服务
     *
     * @return
     */
    public boolean hasEnabledServices() {
        return !correctionServiceMap.isEmpty();
    }

    /**
     * 获取所有开启的服务
     *
     * @return
     */
    public Map<CorrectionModel, AiCorrectionService> getEnabledServices() {
        return correctionServiceMap;
    }
}
